package com.ruoyi.service.impl;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.benmanes.caffeine.cache.Caffeine;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.domain.model.RegisterBody;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.domain.*;
import com.ruoyi.framework.web.service.SysRegisterService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.mapper.T07Mapper;
import com.ruoyi.service.*;
import com.ruoyi.system.service.ISysConfigService;
import com.ruoyi.system.service.ISysRoleService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.system.service.impl.SysRoleServiceImpl;
import com.ruoyi.uitity.MinioUtil;
import com.ruoyi.uitity.SensitiveTextCleaner;
import com.ruoyi.uitity.WxMessageProducer;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.*;

@Service
public class AiServiceImpl implements AIService {

    private com.github.benmanes.caffeine.cache.Cache<String, String> cache = Caffeine.newBuilder()
            .maximumSize(1000) // 设置最大容量
            .expireAfterWrite(10, TimeUnit.MINUTES) // 设置过期时间
            .build();
    @Autowired
    private TokenService tokenService;
    @Autowired
    private IT06Service t06Service;
    @Autowired
    private IT07Service t07Service;
    @Autowired
    private WxMessageProducer producer;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private ISysUserService userService;

    @Autowired
    private IT03Service t03Service;

    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private T07Mapper t07Mapper;
    @Autowired
    private IT05Service t05Service;

    private final ExecutorService executor = Executors.newFixedThreadPool(10);
    @Transactional
    @Override
    public AjaxResult wenda(String str, HttpServletRequest request) throws JsonProcessingException, ExecutionException, InterruptedException {

        ObjectMapper objectMapper = new ObjectMapper();

        // 将JSON字符串解析为JsonNode
        JsonNode jsonNode = objectMapper.readTree(str);

        // 获取content字段的值
        str = jsonNode.get("content").asText();
        //数据清洗
        str = SensitiveTextCleaner.cleanText(str);
        LoginUser loginUser = tokenService.getLoginUser(request);
        Long userId = loginUser.getUserId();
        T06 t06 = t06Service.selectT06ByF0601(userId);
        if(t06.getF0610()==0){
            return new AjaxResult(500, "请先授权");
        }
        T07 t07 = new T07();
        t07.setF0601(userId);
        t07.setF0703(str);
        Date date = new Date();
        t07.setF0704(date);
        t07.setF0705("");
        t07.setF0707(t06.getF0602());
        t07.setF0301(t06.getF0301());
        t07.setF0501(t06.getF0501());
        t07.setF0708(t06.getF0618());
        t07.setF0709(t06.getF0617());

        String answer = cache.getIfPresent(str);
        if (answer != null) {
            t07.setF0706(0L);
            t07Service.insertT07(t07);
            return AjaxResult.success(answer);
        }

        String result = (String) redisTemplate.opsForValue().get(str + userId);
        if (result != null) {
            cache.put(str, result);
            t07.setF0706(0L);
            t07Service.insertT07(t07);
            return AjaxResult.success(result);
        }

        if (t06.getF0611() <= 0) {
            return new AjaxResult(402, "请先充值");
        }


        String response = "";

        response = producer.sendMessage(str, userId);

        // 异步更新缓存和数据库
        String finalStr1 = str;
        String finalResponse = response;
        CompletableFuture<Void> updateFuture = CompletableFuture.runAsync(() -> {
            cache.put(finalStr1 + userId, finalResponse);
            redisTemplate.opsForValue().set(finalStr1 + userId, finalResponse, 10, TimeUnit.MINUTES);
            redisTemplate.opsForValue().set("loginuser:" + t06.getF0601(), t06Service.selectT06ByF0601(t06.getF0601()), 30, TimeUnit.MINUTES);
        }, executor);


        updateFuture.get();

        int count = finalStr1.length();
        Long compId = t06.getF0301();
        T03 t03 = t03Service.selectT03ByF0301(compId);
        count  = (int) (count * t03.getF0306());
        t03.setF0312(t03.getF0312() + count);
        t03.setF0311(t03.getF0311() + 1L);
        t03Service.updateT03(t03);

        if (count > t06.getF0611()) {
            t06.setF0611(0L);
        } else {
            t06.setF0605(t06.getF0605() + count);
            t06.setF0611(t06.getF0611() - count);
        }
        t06Service.updateT06(t06);
        t07.setF0706((long) count);
        t07Service.insertT07(t07);

        return AjaxResult.success(response);

    }
    @Autowired
    private SysRegisterService registerService;
    @Autowired
    private SysRoleServiceImpl sysRoleService;

    @Transactional
    @Override
    public String register(RegisterBody  registerBodyBody) {
        String msg=registerService.register(registerBodyBody);
        SysUser user =userService.selectUserByUserName(registerBodyBody.getUsername());
        Long userId = user.getUserId();
        user.setNickName(registerBodyBody.getName());
        userService.updateUser(user);
        if(!t06Service.checkUserNameUnique(registerBodyBody.getUsername())){
            return  "用户名重复";
        }
        T06 t06 = new T06();
        Date date = new Date();
        t06.setF0602(registerBodyBody.getName());
        t06.setF0601(userId);
        t06.setF0615(date);
        t06.setF0610(1L);
        t06.setF0605(0L);
        t06.setF0606(0L);
        t06.setF0611(0L);
        t06.setF0612(4L);
        t06.setF0616("DEFULTIMG.png");
        t06.setF0611(Sendnumber.SENDNUMBER);
        t06.setF0603(registerBodyBody.getUsername());
        t06.setF0608(SecurityUtils.encryptPassword(registerBodyBody.getPassword()));
        t06.setOpenid(registerBodyBody.getOpenid());
        System.out.println(t06.toString());
        int s =t06Service.insertT06(t06);
        Long  lon[] = new Long[1];
        lon[0] = userId;
        sysRoleService.insertAuthUsers(2L,lon);
        if(msg.isEmpty()){
            return "";
        }
        return msg;
    }

    @Override
    public boolean updateUserImg(MultipartFile file, Long userId,String filename) {
        T06 t06 = t06Service.selectT06ByF0601(userId);
        String oldname = t06.getF0616();
//        t06.setF0616(filename);
//        t06Service.updateT06(t06);
        try {
            minioUtil.upload(file, filename);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    @Override
    public List<QUTH> QueryTrends(Long userId) {
        List<QUTH> list=t07Mapper.QueryTrends(userId);
        return list;
    }

    @Override
    public List<T03> getT03List() {
        return t03Service.selectT03List(new T03());
    }

    @Override
    public List<T05> getT05List(Long comId) {
        return t05Service.getT05List(comId);
    }

    @Override
    public int updateById(T06small t06small, Long F0601) {
        SysUser user = userService.selectUserById(F0601);
        user.setDeptId(t06small.getF0501());
        user.setPhonenumber(t06small.getF0604());
        user.setNickName(t06small.getF0602());
        userService.updateUser(user);
        return t06Service.updateById(t06small,F0601);
    }

    @Override
    public List<String> getHot(HttpServletRequest request) {
        Long userId=tokenService.getLoginUser(request).getUserId();
        T06 t06 = t06Service.selectT06ByF0601(userId);
        Long ComId = t06.getF0301();
        List<String> result = new ArrayList<>();
        //从数据库查询到 最近的历史记录
        List<T07> list = t07Service.selectlist(userId);
        if(!ObjectUtils.isEmpty(list)){
            for(T07 t07:list){
                result.add(t07.getF0703());
                if(result.size()>=3){
                    break;
                }
            }
        }
        //如果个人的历史记录没有从公司端拿
        if(result.size()<3){
            List<T07> list2 = t07Service.GetComSelect(ComId);
            if(ObjectUtils.isEmpty(list2)){
                for(T07 t07:list2){
                    if(t07.getF0601()==userId){
                        continue;
                    }
                    result.add(t07.getF0703());
                }
            }
        }

        //如果公司端还没有，则系统生成三个
        if(result.size()<3){
            for(int i =1;i<=3-result.size();i++){
                if(i==1){
                    result.add("你好,请告诉我你需要解决的问题");
                }else if(i==2){
                    result.add("需要我告诉你我的功能嘛");
                }else if(i==3){
                    result.add("我是一个很智能的智慧问答AI");
                }
            }
        }
        return  result;
    }
}
